/*
 * vbat电源电压检测――ADC
 */

#include "head\vbat.h"

void vbat_Init()
{
    //Enable A/D channel A0
    GPIO_setAsPeripheralModuleFunctionInputPin(VBAT_ADC12_PORT,GPIO_PIN0);

    //Initialize the ADC12_A Module
    /*
     * Base address of ADC12_A Module
     * Use internal ADC12_A bit as sample/hold signal to start conversion
     * USE MODOSC 5MHZ Digital Oscillator as clock source
     * Use default clock divider of 1
     */
    ADC12_A_init(VBAT_ADC12_BASE,
        ADC12_A_SAMPLEHOLDSOURCE_SC,
        ADC12_A_CLOCKSOURCE_ADC12OSC,
        ADC12_A_CLOCKDIVIDER_1);

   ADC12_A_enable(VBAT_ADC12_BASE);

    /*
     * Base address of ADC12_A Module
     * For memory buffers 0-7 sample/hold for 16 clock cycles
     * For memory buffers 8-15 sample/hold for 4 clock cycles (default)
     * Disable Multiple Sampling
     */
    ADC12_A_setupSamplingTimer(VBAT_ADC12_BASE,
        ADC12_A_CYCLEHOLD_64_CYCLES,
        ADC12_A_CYCLEHOLD_4_CYCLES,
        ADC12_A_MULTIPLESAMPLESDISABLE);

    //Configure Memory Buffer
    /*
     * Base address of the ADC12_A Module
     * Configure memory buffer 0
     * Map input A0 to memory buffer 0
     * Vref+ = VeREF+ (ext)
     * Vref- = AVss
     * Memory buffer 0 is not the end of a sequence
     */
    ADC12_A_configureMemoryParam param = {0};
    param.memoryBufferControlIndex = VBAT_ADC12_MEMORY;
    param.inputSourceSelect = VBAT_ADC12_INPUT;
    param.positiveRefVoltageSourceSelect = ADC12_A_VREFPOS_AVCC;
    param.negativeRefVoltageSourceSelect = ADC12_A_VREFNEG_AVSS;
    param.endOfSequence = ADC12_A_NOTENDOFSEQUENCE;
    ADC12_A_configureMemory(VBAT_ADC12_BASE ,&param);

//    //Configure internal reference
//    //If ref generator busy, WAIT
//    while ( REF_ACTIVE == Ref_isRefGenBusy(REF_BASE) ) ;
//    //Select internal ref = 1.5V
//    Ref_setReferenceVoltage(REF_BASE,REF_VREF1_5V);
//    //Internal Reference ON
//    Ref_enableReferenceVoltage(REF_BASE);

    //Delay (~75us) for Ref to settle
    __delay_cycles(75);
}

void vbat_GetElectricQuantity(uint16_t *pElectrQuan)
{
    //Enable/Start first sampling and conversion cycle
    /*
     * Base address of ADC12_A Module
     * Start the conversion into memory buffer 0
     * Use the single-channel, single-conversion mode
     */
    ADC12_A_startConversion(VBAT_ADC12_BASE,
                            VBAT_ADC12_MEMORY,
                            ADC12_A_SINGLECHANNEL);

    //Poll for interrupt on memory buffer 0
    while (!ADC12_A_getInterruptStatus(VBAT_ADC12_BASE,VBAT_ADC12_IFG)) ;

    //满量程是2的12次方，4096
    *pElectrQuan = ADC12_A_getResults(VBAT_ADC12_BASE,VBAT_ADC12_MEMORY);
    __no_operation();
}

void vbat_GetVoltage(uint16_t *v)
{
    uint16_t eleQuan;
    vbat_GetElectricQuantity(&eleQuan);
    float a = (float)eleQuan * (float)(33.0 / 15.0);
    float b = a * 15.0 * 9.0;
    float c = 4096.0;
    *v = (uint16_t)((b/c)+0.5);
    __no_operation();
}
